import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/entity/count_entity.dart';
import 'package:shopping_group/entity/selectiont_entity.dart';
import 'package:shopping_group/modle/login/bloc/user_certification_bloc.dart';
import 'package:shopping_group/modle/login/bloc/user_login_bloc.dart';
import 'package:shopping_group/modle/login/ui/user_register_page.dart';
import 'package:shopping_group/modle/person/ui/about_page.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/image_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/shared_preferences_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';

import 'userxy_about_page.dart';
import 'userys_about_page.dart';

class UserLoginPage extends StatefulWidget {
  @override
  _TaskBlockInfoViewState createState() => _TaskBlockInfoViewState();
}

class _TaskBlockInfoViewState extends State<UserLoginPage> {
  TextEditingController _controllerName = TextEditingController();
  TextEditingController _controllerCode = TextEditingController();
  TextEditingController _controllerPwd = TextEditingController();
  bool isSecrecy = true;
  bool _isDxLogin = false;
  UserLoginBloc _bloc;
  SelectiontEntity _selection = SelectiontEntity();
  CountEntity _countEntity = CountEntity();
  UserCertificationBloc _certificationBloc;
  @override
  void initState() {
    super.initState();
    _selection = SelectiontEntity()..title = '同意《注册服务协议》和《隐私政策》';
    _bloc = UserLoginBloc();
    _certificationBloc = UserCertificationBloc();
    Future.wait([
      SharedPreferencesUtil.readShared('userName').then((name) {
        setState(() {
          _controllerName.text = name;
        });
      }),
      SharedPreferencesUtil.readShared('password').then((password) {
        setState(() {
          _controllerPwd.text = password;
        });
      }),
    ]).then((value) {
      if (!ObjectUtil.isEmptyString(_controllerName.text) &&
          !ObjectUtil.isEmptyString(_controllerPwd.text)) {
        Map<String, dynamic> data = new Map<String, dynamic>();
        data['codeOrPhone'] = _controllerName.text;
        data['pwd'] = _controllerPwd.text;
        data['loginType'] = BaseConstant.PWD;
        data['validateCode'] = '';
        data['isDxLogin'] = 'N';
        _bloc.cilkeLoginAction.add(data);
      }
    });

    // fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
    //   if (res is fluwx.WeChatAuthResponse) {
    //     Map<String, dynamic> map = {};
    //     map['appid'] = BaseConstant.appId.trim();
    //     map['secret'] = BaseConstant.appSecret.trim();
    //     map['code'] = res.code.trim();
    //     map['grant_type'] = 'authorization_code';
    //     _bloc.openidAction.add(map);
    //   }
    // });
    //  _onChannel();
  }

  // void _onChannel() {
  //   _methodChannel = MethodChannel(BaseConstant.CHANNEL_WX_METHOD);
  //   _initWx();
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          height: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white,
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colours.clipRRect_xujian,
                  Colours.themeColor,
                ]),
          ),
          child: Column(
            children: <Widget>[
              Container(
                padding: const EdgeInsets.only(top: 90, bottom: 75),
                alignment: const FractionalOffset(0.2, 0),
                child: WidgetUtils.getTextColorView(
                    '欢迎使用利正生活', Colours.gray_33, Dimens.FONT_SIZE_30),
              ),
              Column(
                children: <Widget>[
                  _loginBody(),
                  _bottomWidget(),
                  SizedBox(
                    height: 42,
                  ),
                  GestureDetector(
                    onTap: () {
                      RouteUtil.goParameter(AboutDialogPage());
                    },
                    child: WidgetUtils.getTextColorView(
                      '关于利正生活',
                      Colours.gray_33,
                      Dimens.FONT_SIZE_18,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ],
              ),
              // flex: 3,
            ],
          ),
        ),
      ),
    );

    // body: );
  }

  Widget _loginBody() {
    return Container(
      margin: const EdgeInsets.only(left: 6, right: 6),
      child: Column(
        children: <Widget>[
          WidgetUtils.buildTextField(
              _controllerName,
              TextInputType.number,
              '手机号',
              List<TextInputFormatter>()
                ..add(LengthLimitingTextInputFormatter(18)),
              Icons.account_box,
              iconColor: Colours.blackground_black_bf,
              textColor: Colours.gray_33,
              hitColor: Colours.blackground_black_bf),
          Container(
            margin: const EdgeInsets.only(left: 12, right: 12),
            child: WidgetUtils.drawDivider(
                color: Colours.title_white, height: 1.0),
          ),
          isDxOrPasswordView(),
          Container(
            margin: const EdgeInsets.only(left: 12, right: 12),
            child: WidgetUtils.drawDivider(
                color: Colours.title_white, height: 1.0),
          ),
          SizedBox(
            height: 16,
          ),
          GestureDetector(
            onTap: () {
              setState(() {
                _isDxLogin = !_isDxLogin;
              });
            },
            child: Container(
              padding: const EdgeInsets.only(
                right: 32,
              ),
              alignment: Alignment.centerRight,
              child: WidgetUtils.getTextColorView(_isDxLogin ? '密码登录' : '验证码登录',
                  Colours.gray_33, Dimens.FONT_SIZE_14),
            ),
          ),
          SizedBox(
            height: 50,
          ),
          Row(
            children: <Widget>[
              SizedBox(
                width: 16,
              ),
              GestureDetector(
                onTap: () {
                  RouteUtil.goParameter(UserXyAboutPage());
                },
                child: WidgetUtils.getTextColorView(
                  '查看注册协议',
                  Colours.gray_33,
                  Dimens.FONT_SIZE_10,
                  decoration: TextDecoration.underline,
                ),
              ),
              SizedBox(
                width: 24,
              ),
              GestureDetector(
                onTap: () {
                  RouteUtil.goParameter(UserYsAboutPage());
                },
                child: WidgetUtils.getTextColorView(
                  '查看隐私协议',
                  Colours.gray_33,
                  Dimens.FONT_SIZE_10,
                  decoration: TextDecoration.underline,
                ),
              ),
            ],
          ),
          SizedBox(
            height: 8,
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: _showXyView(_selection),
              ),
              SizedBox(
                width: 16,
              ),
            ],
          ),
          SizedBox(
            height: 8,
          ),
          ButtonProgressView.crateCupertinoView('快速登录',
              horizontalPadding: 8,
              textColor: Colours.gray_33,
              blackColor: Colours.title_white, cupertinoCall: () {
            //RouteUtil.goView(PageConstance.MAIN_PAGE);
            String username = _controllerName.text;
            String password = _controllerPwd.text;
            String code = _controllerCode.text;
            if (username.isEmpty) {
              BotToast.showText(text: '请输入用户名');
              return;
            }

            if (username.length < 5) {
              BotToast.showText(text: '用户名至少5位');
              return;
            }
            if (!_isDxLogin) {
              if (password.isEmpty) {
                BotToast.showText(text: '请输入密码');
                return;
              }
              if (password.length < 6) {
                BotToast.showText(text: '密码至少6位');
                return;
              }
            } else {
              if (code.isEmpty) {
                BotToast.showText(text: '请输入短信验证码');
                return;
              }
              if (code.length < 5) {
                BotToast.showText(text: '密码至少5位');
                return;
              }
            }

            if (!_selection.isSelect) {
              BotToast.showText(text: '请同意服务协议');
              return;
            }

            Map<String, dynamic> data = new Map<String, dynamic>();
            data['codeOrPhone'] = username;
            data['pwd'] = password;
            data['loginType'] = _isDxLogin ? BaseConstant.DX : BaseConstant.PWD;
            data['validateCode'] = _controllerCode.text;
            data['isDxLogin'] = _isDxLogin ? 'Y' : 'N';
            _bloc.cilkeLoginAction.add(data);
          }),
        ],
      ),
    );
  }

  Widget isDxOrPasswordView() {
    return Column(
      children: <Widget>[
        Offstage(
          offstage: !_isDxLogin,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              // Expanded(
              //   flex: 1,
              //   child: Container(
              //     padding: const EdgeInsets.only(left: 16),
              //     alignment: FractionalOffset.centerLeft,
              //     child: WidgetUtils.getTextColorView(
              //         '验证码：', Colours.title_white, Dimens.FONT_SIZE_16),
              //   ),
              // ),
              Expanded(
                child: StreamBuilder(
                  stream: _certificationBloc.pushDate,
                  initialData: _countEntity,
                  builder:
                      (BuildContext context, AsyncSnapshot<Object> snapshot) {
                    Object object = snapshot.data;
                    if (object is CountEntity) {
                      _countEntity = object;
                    }
                    return Padding(
                      padding:
                          const EdgeInsets.only(left: 16, top: 16, bottom: 16),
                      child: WidgetUtils.buildTextFieldCode(
                          _controllerCode,
                          TextInputType.phone,
                          '请输入验证码',
                          List<TextInputFormatter>()
                            ..add(LengthLimitingTextInputFormatter(18)),
                          _countEntity.codeCountdownStr,
                          Colours.blackground_609,
                          hitColor: Colours.title_white,
                          textColor: Colours.title_white,
                          codeCallback: (callback) {
                        _usercode();
                      }),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
        Offstage(
            offstage: _isDxLogin,
            child: WidgetUtils.buildTextField(
                _controllerPwd,
                TextInputType.text,
                '密码',
                List<TextInputFormatter>()
                  ..add(LengthLimitingTextInputFormatter(18)),
                Icons.lock,
                isSecrecy: true,
                iconColor: Colours.blackground_black_bf,
                textColor: Colours.gray_33,
                hitColor: Colours.blackground_black_bf)),
      ],
    );
  }

  //校验获取验证码格式
  void _usercode() {
    String phonename = _controllerName.text;
    if (ObjectUtil.isEmptyString(phonename)) {
      BotToast.showText(text: '请输入您的手机号');
      return;
    }
    if (phonename.length != 11) {
      BotToast.showText(text: '请输入正确的手机号');
      return;
    }

    _certificationBloc.verificationDate.add(phonename);
  }

  Widget _showXyView(SelectiontEntity entity) {
    return WidgetUtils.getCheckboxIocnView(entity,
        textColor: Colours.gray_33, iconsColor: Colours.gray_33, blackCall: () {
      setState(() {
        entity.isSelect = !entity.isSelect;
      });
    }, verticalPadding: 0);
  }

  Widget _bottomWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(left: 32, right: 32, top: 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              GestureDetector(
                onTap: (() {
                  RouteUtil.goView(PageConstance.FIND_PASSWORD_PAGE);
                }),
                child: WidgetUtils.getTextColorView(
                    '忘记密码', Colours.gray_33, Dimens.FONT_SIZE_14),
              ),
              GestureDetector(
                onTap: (() {
                  RouteUtil.goParameter(UserRegisterPage());
                }),
                child: WidgetUtils.getTextColorView(
                    '没有帐号？去注册', Colours.gray_33, Dimens.FONT_SIZE_14),
              ),
            ],
          ),
        ),

        //  _wxLogin(),
      ],
    );
  }

  Widget _wxLogin() {
    return GestureDetector(
        onTap: () {
          fluwx
              .sendWeChatAuth(
                  scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
              .then((data) {
            setState(() {
              // BotToast.showText(text: "拉取微信用户信息：" + data.toString());
            });
          }).catchError((e) {
            print('weChatLogin  e  $e');
          });
          // _wxFLogin();
        },
        child: Container(
          color: Colors.transparent,
          margin: const EdgeInsets.only(top: 32),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ImageUtils.imageNetwork(
                  'http://quanmp.oss-cn-shenzhen.aliyuncs.com/static/images/2login/signin_icon_wechat.png'),
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: WidgetUtils.getTextColorView(
                    '微信登录', Colours.text_91, Dimens.FONT_SIZE_15),
              ),
            ],
          ),
        ));
  }

  // Future<void> _initWx() async {
  //   return await _methodChannel.invokeMethod('initWx');
  // }

  // Future<void> _wxFLogin() async {
  //   return await _methodChannel.invokeMethod('wxLogin');
  // }

  @override
  void dispose() {
    _controllerName.dispose();
    _controllerPwd.dispose();
    _bloc.dispose();
    super.dispose();
  }
}
